package jupiter.channel;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jupiter.filters.*;
/**
 * Helper for getting data out of an address in the form
 * 
 * @author Justin
 * 
 */
public class Address {
	
	private static Pattern addressPattern = Pattern.compile("^([^/@]+)(/[^#@]*)?(#[^@]*)?@(.+)$");
	
	
	private String address;
	
	private String domain;
	private String channel;
	private String hash;
	private String host; // should almost always be jabbify.com
	
	public Address(String a) throws FilterException {
		
		address = a;
		Matcher matcher = addressPattern.matcher(a);

		if(!matcher.find())
			throw new FilterException("{error: 'unable to parse address: "+a+"'}");
		
		domain = matcher.group(1).toLowerCase();
		channel = matcher.group(2) != null ? matcher.group(2).toLowerCase() : "/"; //in case it is blank
		hash = matcher.group(3) != null ? matcher.group(3).toLowerCase() : null;
		host = matcher.group(4).toLowerCase();
		//set back to make sure channel has / 
		address= domain+channel+(hash != null ? this.hash : "")+"@"+host;
	}
	
	/*
	 * The domain this user is on (javascriptmvc.com)
	 */
	public String domain(){
		return domain;
	}
	public String channel(){
		return channel;
	}
	public String hash(){
		return hash;
	}
	public String host(){
		return host;
	}
	
	public Address hashlessAddress() throws FilterException {
		return new Address( domain+channel+"@"+host   );
	}
	
	public Address domainAddress() throws FilterException {
		return new Address( domain+"@"+host   );
	}
	
	public String toString(){
		return address;
	}
}
